package com.example.telesys.test;

import com.example.telesys.RocketMQTransactionEntity.TxLog;
import com.example.telesys.mapper.TxLogMapper;
import com.example.telesys.pojo.Supplier;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Service;

@Service
@RocketMQTransactionListener(txProducerGroup = "tx_producer_group")
public class SendTransactionMessageListener implements RocketMQLocalTransactionListener {

    @Autowired
    private SendTransactionMessage sendTransactionMessage;

    @Autowired
    private TxLogMapper txLogMapper;

    /**
     * 执行本地事务
     *
     * @param message 发送事务消息时MessageBuilder后的内容
     * @param o       发送事务消息的具体消息内容
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        String txLogId = (String) message.getHeaders().get("txLogId");
        try {
            Supplier supplier = (Supplier) o;
            sendTransactionMessage.createSupplier(txLogId, supplier);
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    /**
     * 消息回查
     *
     * @param message
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        String txLogId = (String) message.getHeaders().get("txLogId");
        TxLog txLog = txLogMapper.findById(txLogId);
        //如果本地事务成功 就上报给服务端
        if (txLog != null) {
            return RocketMQLocalTransactionState.COMMIT;
        }else{
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
}
